<template>
  <div class="app-breadcrumb-wrapper">
    <div class="app-breadcrumb">
      <!-- 首页固定 -->
      <div class="breadcrumb-item" :class="{ 'active': $route.path === '/dashboard' }">
        <a @click.prevent="handleLink({ path: '/dashboard' })">首页</a>
      </div>

      <!-- 其他路由项 -->
      <div v-for="(item, index) in levelList" :key="item.path" class="breadcrumb-item"
        :class="{ 'active': $route.path === item.path }">
        <a @click.prevent="handleLink(item)">
          {{ item.meta.title }}
        </a>
        <!-- 关闭按钮 -->
        <el-button type="text" icon="el-icon-close" @click.prevent="removeBreadcrumb(index, item.path)"></el-button>
      </div>
    </div>
    <!-- 关闭全部按钮 -->
    <el-button type="primary" size="small" class="clear-all-btn" @click="clearBreadcrumbs">关闭全部</el-button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      levelList: [], // 记录所有独立访问的路由（不包括首页）
      singleRoutePrefixes: ['siyuanDetail', 'customerDetail', 'productionDetail', 'addSctk', 'questions', 'addExamPaper', 'examQuestions'] //单例路由
    }
  },
  watch: {
    $route(to) {
      this.addBreadcrumb(to);
    }
  },
  created() {
    this.addBreadcrumb(this.$route); // 初始化时添加当前路由
  },
  methods: {
    addBreadcrumb(route) {
      // 检查当前路由是否属于需要特殊处理的路由
      const isSingleRoute = this.singleRoutePrefixes.some(prefix => route.path.startsWith(`/${prefix}`));

      if (isSingleRoute) {
        // 获取单例路由后面的路径部分
        const pathSegments = route.path.split('/').filter(Boolean); // 分割路径并去掉空字符串
        const lastSegment = pathSegments[pathSegments.length - 1]; // 获取最后一个路径段
        // 判断最后一个路径段是否为数字（ID）
        const isId = /^\d+$/.test(lastSegment);
        if (!isId) {
          const newPath = `/${lastSegment}`;
          // 手动解析目标路由的 meta 数据
          const resolvedRoute = this.$router.resolve(newPath).route;
          const isExist = this.levelList.find(item => item.path === newPath);

          if (!isExist && route.path !== '/dashboard') {
            // 记录新的面包屑
            this.levelList.push({
              path: newPath,
              meta: { title: resolvedRoute.meta.title || '无标题' }
            });
          }
          this.$router.push(newPath);
          return;
        } else {
          // 如果是带 ID 的路径（如 /siyuanDetail/6），确保它不会被重复添加
          // 移除之前存储的相同类型的单例路由
          const isExist = this.levelList.find(item => item.path === route.fullPath);
          if (!isExist && route.path !== '/dashboard') {
            this.levelList = this.levelList.filter(item => {
              return !this.singleRoutePrefixes.some(prefix => item.path.startsWith(`/${prefix}`));
            });
            this.levelList.push({
              path: route.fullPath, // 使用 fullPath 而不是 path
              meta: { title: route.meta.title || '无标题' }
            });
          } else {
            this.$router.push(route.fullPath);
          }

        }
      } else {
        // 对于普通路由（如 /userSetting），直接添加到面包屑列表

        const isExist = this.levelList.find(item => item.path === route.fullPath);
        if (!isExist && route.path !== '/dashboard') {
          this.levelList.push({
            path: route.fullPath, // 使用 fullPath 而不是 path
            meta: { title: route.meta.title || '无标题' }
          });
        }
      }
    },
    handleLink(item) {
      this.$router.push(item.path);
    },
    removeBreadcrumb(index, path) {
      if (this.$route.path === path) {
        // 如果删除的是当前页面，则跳转到首页
        this.$router.push('/dashboard');
      }
      this.levelList.splice(index, 1);
    },
    clearBreadcrumbs() {
      // 清空除了首页以外的所有面包屑项
      this.levelList = [];
      // 如果当前不在首页，则跳转到首页
      if (this.$route.path !== '/dashboard') {
        this.$router.push('/dashboard');
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.app-breadcrumb-wrapper {
  display: flex;
  justify-content: space-between;
  /* 使子元素分散对齐 */
  align-items: center;
  width: 100%;

  .app-breadcrumb {
    display: flex;
    align-items: center;
    margin-left: 8px;
    overflow-x: auto;
    /* 如果内容超出宽度则允许滚动 */

    .breadcrumb-item {
      display: flex;
      align-items: center;
      margin-top: 10px;
      padding: 5px 10px;
      // border: 1px solid #dcdfe6;
      border-radius: 4px;
      margin-right: 8px;
      cursor: pointer;

      &.active {
        box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.1),
          inset 0px 2px 4px rgba(0, 0, 0, 0.1);
        /* 绿色背景 */
        color: white;
        // border-color: #67c23a;
      }

      a {
        color: #606266;
        text-decoration: none;
      }

      .el-button--text {
        padding: 0;
        margin-left: 8px;
        font-size: 12px;
      }
    }
  }

  .clear-all-btn {
    margin-right: 16px;
    /* 给按钮右边留出空间 */
    align-self: flex-end;
    /* 对齐到容器的底部 */
  }
}
</style>